package com.example.ktapplication.net.interceptor

import com.elvishew.xlog.XLog
import com.example.ktapplication.utils.event.Event
import com.example.ktapplication.utils.event.EventBusUtil
import com.example.ktapplication.utils.toJson
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException

class ResponseInterceptor:Interceptor {

    //后台返回的需要登录的状态码的KEY值
    val NEED_LOGIN_KEY: String
        get() = "errorCode"
    val NEED_LOGIN: Int
        get() = -1001

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request: Request = chain.request()
        val response: Response = chain.proceed(request)
        val requestUrl = request.url.toString()
        val responseBody = response.body
        //获取返回值类型
        val mediaType = responseBody!!.contentType()
        //获取Response.body()的数据为数据流，只能获取一次，在获取之后数据流会关闭，再次获取会有异常抛出
        val responseBytes = responseBody.bytes()
        //利用修改后的返回值，构造新的相应体
        val response2 = response.newBuilder()
            .body(ResponseBody.create(mediaType, responseBytes))
            .build()
        val response3 = response.newBuilder()
            .body(ResponseBody.create(mediaType, responseBytes))
            .build()
        response3.body?.string()?.let { body ->
            // 打印响应体内容
            XLog.json(body)
        }
        /**
         * 当前请求的url是否需要cookie(token)
         * 1:需要cookie(token)的进行拦截
         * 2：不需要的直接返回
         */
        //使用需要cookie(token)的接口,则需要先登录账号(跳转至登录页面)
        if (response.code == 200) {
            try {
                val jsonObject = JSONObject(response2.body!!.string())
                //这里要对应该后台返回的json字段的key
                val errorCode = jsonObject.getString(NEED_LOGIN_KEY).toInt()
                //这里要对应好后台的状态码(-1001是玩android接口的需要登录的状态码)
                if (errorCode == NEED_LOGIN) {
                    //跳转至登录页面
                    EventBusUtil.eventBus.post(Event.NeedLogin())
                }
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }
        val returnResponse =
            response.newBuilder().body(ResponseBody.create(mediaType, responseBytes))
                .build()
        return returnResponse
    }
}